#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
//int main()
//{
 //printf("我的程序要运行咯\n");
//  excel("/usr/bin/ls","ls","-l","-a",NULL);
//  excel("/usr/bin/top",NULL);
//  printf("我的程序运行完了");
 // return 0;
//}


//函数指针类型
//typedef void (*func_t)();
//#define  Num 5
//func_t handlers[Num+1];
//如下是任务
void Download()
{
  printf("Download：");
}
void Flush()
{
  printf("Flush:");
}
void Log()
{
  printf("Log:");
}

//注册
void registerHandler(func_t h[],func_t f)
{
  int i = 0;
  for(; i < Num;i++)
  {
    if(h[i] == NULL) break;
  }
  if(i == Num) return ;
  h[i] = f;
  h[i+1] = NULL;
}
int main()
{
  registerHandler(handlers,Download);
  registerHandler(handlers,Flush);
  registerHandler(handlers,Log);

  pid_t id = fork();
  if(id == 0)
  {
    int cnt = 3;
    while(1)
    {
      sleep(3);
      printf("我是一个子进程,pid:%d,ppid:%d",getpid(),getppid());
      sleep(1);
      cnt--;
      int* p = 0;
      *p = 100;
      int a = 10;
     // a/=0;
    }
    exit(10);
  }
  while(1)
  {
    int status = 0;
    pid_t rid = waitpid(id,&status,WNOHANG);
    if(rid > 0)
    {
      printf("wait success,rid:%d,exit code:%d,exit signal:%d",rid,(status>>8)&0xFF,status&0x7F);
      break;
    }
    else if(rid == 0)
    {
      int i= 0;
      for(;handlers[i];i++)
      {
        handlers[i];
      }
      printf("本轮调用结束，子进程没有退出\n");
      sleep(1);
    }
    else{
      printf("等待失败");
      break;
    }
  }
  
  pid_t rid = wait(NULL);
  int status = 0;
  pid_t rid = waitpid(id,&status,0);
  if(rid>0)
  {
    if(WIFEXITED(status))
    {
      printf("wati success,rid:%d,exit code:%d,exit signal:%d",rid,WEXITSTATUS(status),status&0x7F);
    }
    else{
      printf("子进程退出异常");
      printf("wait success ,rid:%d,exit code:%d,exit signal:%d",rid,(status>>8)&0xFF,status&0x7F);
    }
}
  else{
    printf("wait failed:%d:%s\n",errno,strerror(errno));
}
return 0;
}
void func()
{
  printf("fun begin");
  _exit(4);
  printf("fun end!");
}
int main()
{
  func();
  printf("main!");
  sleep(2);
  _exit(23);
  int i = 0;
  for(; i < 200;i++)
  {
    printf("%d->%s",i,strerror(i));
  }
  printf("hello world");
  FILE* fp = fopen("log.txt","r");
  if(fp == nullptr) return 13;
  fclose(fp);
  return 0;
}

